<!--
 * @Description: 节流
 * @version: 1.0
 * @Author: ziwei
 * @Date: 2021-10-12 23:18:55
 * @LastEditors: ziwei
 * @LastEditTime: 2021-10-15 14:16:42
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="btn" style="background: red;color: #FFF;display: inline-block;padding: 10px;">点击节流</button>
  <script>
    // 但是最后一次点击不会执行 我期望最后一次也能执行
    function throttle(func, wait, options)
    {
      let args, context, previous = 0, timeout;
      let throttled = function (params)
      {
        args = arguments;
        context = this;
        let now = new Date();
        if(!previous&&options.leading){previous=now}
        let remaining = wait - (now - previous);
        if (remaining <= 0) {
          if (timeout) {
            clearTimeout(timeout)
            timeout = null
          }
          func.apply(this, arguments);
          previous = now;
        } else if (!timeout) {
          timeout = setTimeout(() =>
          {
            previous = options.leading?0:now
            func.apply(this, arguments);
          }, remaining);
        }
      }
      return throttled
    }
    // function throttle(fun, wait)
    // {
    //   let previous = 0;
    //   return function ()
    //   {
    //     let now = new Date();
    //     if (now - previous > wait) {
    //       fun.apply(this, arguments)
    //       previous = now;
    //     }
    //   }
    // }

    function logger()
    {
      console.log('点击点击点击');
    }
    btn.addEventListener('click', throttle(logger, 1000, { trailing: true,leading:true }));
  </script>
</body>

</html>